//
//  NewADTools.swift
//  YongQingFont
//
//  Created by 李东 on 2024/7/19.
//

import UIKit
import AnyThinkSDK
import AnyThinkBanner
import AnyThinkSplash
import AnyThinkRewardedVideo
import AnyThinkInterstitial
import SnapKit

enum ADType {
    case OPEN
    case FULL_SCREEN
    case BANNER
    case REWARD_VIDEO
}

extension Notification.Name {
    static let ShowFullScrrenAD = Notification.Name.init(rawValue: "ShowFullScrrenAD")
    static let SDKInitFinish = Notification.Name.init(rawValue: "SDKInitFinish")
}

///TopOn广告聚合
class NewADTools: NSObject {

    
    static let isTest = false
    
    static let TEST_APP_KEY = "aa362875ba97e674560d29457fda0c1a5"
    static let APP_KEY = "a5150bf745b60bafd19848d773cde5377"
    
    static let TEST_APP_ID = "h6693754352cda"
    static let TEST_BANNER_ID = "n6693757bac97e"
    static let TEST_FULLSCREEN_ID = "n669375859fbc5"
    static let TEST_OPEN_ID = "n6693758c7c55f"
    static let TEST_VIDEO_ID = "n6693759358499"
    
    static let APP_ID = "h6698be753b543"
    static let BANNER_ID = "n6698befb4554c"
    static let FULLSCREEN_ID = "n6698befba2c5b"
    static let OPEN_ID = "n6698befbd0ea9"
    static let VIDEO_ID = "n6698befb71caf"
    
    static var initFinish = false
    
    var currentType = ADType.OPEN
    
    var bannerView: ATBannerView?
    var currentVC: UIViewController?
    var finishVideoCallBack:(() -> Void)?
    var didCloseFullScreenCallBack:(() -> Void)?
    var isShowFullScreen = false
    
    static func sdkInit() {
        ATAPI.setLogEnabled(isTest)
        let appID = isTest ? TEST_APP_ID : APP_ID
        let appKey = isTest ? TEST_APP_KEY : APP_KEY
        
        do {
            try? ATAPI.sharedInstance().start(withAppID: appID, appKey: appKey)
            initFinish = true
            NotificationCenter.default.post(name: .SDKInitFinish, object: nil)
        }

    }
    
    ///加载广告
    func loadAD(type: ADType) {
        loadAD(type: type, vc: nil)
    }
    
    func loadAD(type: ADType, vc: UIViewController?) {
        currentType = type
        currentVC = vc == nil ? getCurrentVC() : vc
        if type == .BANNER {
            ATAdManager.shared().loadAD(withPlacementID: getADPlaceID(type: currentType), extra: [kATAdLoadingExtraBannerAdSizeKey: CGSize(width: CGFloat.screenWidth, height: 70)], delegate: self)
        }else{
            ATAdManager.shared().loadAD(withPlacementID: getADPlaceID(type: currentType), extra: [:], delegate: self)
        }
    }
    
    
    func getADPlaceID(type: ADType) -> String {
        switch type {
        case .OPEN: 
            return NewADTools.isTest ? NewADTools.TEST_OPEN_ID : NewADTools.OPEN_ID
        case .BANNER: 
            return NewADTools.isTest ? NewADTools.TEST_BANNER_ID : NewADTools.BANNER_ID
        case .FULL_SCREEN:
            return NewADTools.isTest ? NewADTools.TEST_FULLSCREEN_ID : NewADTools.FULLSCREEN_ID
        case .REWARD_VIDEO: 
            return NewADTools.isTest ? NewADTools.TEST_VIDEO_ID : NewADTools.VIDEO_ID
        }
    }
    
    func showOpenAD(placementID: String) {
        if ATAdManager.shared().splashReady(forPlacementID: placementID) {
            ATAdManager.shared().showSplash(withPlacementID: placementID, scene: "", window: nomalWindow(), delegate: self)
        }
    }
    
    func showBannerAD(placementID: String) {
        if ATAdManager.shared().bannerAdReady(forPlacementID: placementID) {
            bannerView?.removeFromSuperview()
            bannerView = ATAdManager.shared().retrieveBannerView(forPlacementID: placementID)
            if bannerView != nil {
//                bannerView!.delegate = self
                bannerView!.presentingViewController = currentVC
                bannerView!.translatesAutoresizingMaskIntoConstraints = false
                currentVC!.view.addSubview(bannerView!)
                bannerView!.snp.makeConstraints({ make in
                    make.left.right.equalToSuperview()
                    make.bottom.equalTo(-CGFloat.bottomPadding)
                    make.height.equalTo(70)
                })
            }
        }
    }
    
    func showRewardVideo(placementID: String) {
        if ATAdManager.shared().rewardedVideoReady(forPlacementID: placementID) {
            ATAdManager.shared().showRewardedVideo(withPlacementID: placementID, in: currentVC!, delegate: self)
        }
    }
    
    func showFullScreen(placementID: String) {
        if isShowFullScreen {
            return
        }
        if ATAdManager.shared().interstitialReady(forPlacementID: placementID) {
            ATAdManager.shared().showInterstitial(withPlacementID: placementID, in: getCurrentVC(), delegate: self)
        }
    }
    
    func nomalWindow() -> UIWindow {
       var window = UIApplication.shared.connectedScenes
            .compactMap { $0 as? UIWindowScene }
            .flatMap { $0.windows }
            .first(where: { $0.isKeyWindow })!
       for item in UIApplication.shared.windows {
           if item.windowLevel == .normal {
               window = item
           }
       }
       return window
   }
        
    func getCurrentVC() ->UIViewController{
        //UIApplication.shared.keyWindow 即将被弃用
        var vc = UIApplication.shared.connectedScenes
            .compactMap { $0 as? UIWindowScene }
            .flatMap { $0.windows }
            .first(where: { $0.isKeyWindow })?.rootViewController
        
        if (vc?.isKind(of: UITabBarController.self))! {
            vc = ((vc as! UITabBarController).selectedViewController as! UINavigationController).visibleViewController
        }else if (vc?.isKind(of: UINavigationController.self))!{
            vc = (vc as! UINavigationController).visibleViewController
        }else if ((vc?.presentedViewController) != nil){
            vc =  vc?.presentedViewController
        }
        
        return vc!
        
    }
}

extension NewADTools: ATAdLoadingDelegate {
    func didFinishLoadingAD(withPlacementID placementID: String!) {
        print("加载成功可以展示")
        if currentType == .OPEN {
            showOpenAD(placementID: placementID)
        } else if currentType == .BANNER {
            showBannerAD(placementID: placementID)
        } else if currentType == .REWARD_VIDEO {
            showRewardVideo(placementID: placementID)
        } else if currentType == .FULL_SCREEN {
            showFullScreen(placementID: placementID)
        }
    }
    
    func didFailToLoadAD(withPlacementID placementID: String!, error: (any Error)!) {
        //加载失败
        print("聚合广告加载失败 placementID = \(String(describing: placementID)), error = \(error.localizedDescription)")
    }
}

extension NewADTools: ATSplashDelegate {
    func splashDidShow(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
        print("开屏广告已展示")
    }
    
    func splashDidClick(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
        print("开屏广告点击了")
    }
    
    func splashDidClose(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
        print("开屏广告关闭了")
    }
    
}

extension NewADTools: ATRewardedVideoDelegate {
    func rewardedVideoDidStartPlaying(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
        
    }
    
    func rewardedVideoDidEndPlaying(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
        
    }
    
    func rewardedVideoDidClick(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
        
    }
    
    func rewardedVideoDidClose(forPlacementID placementID: String, rewarded: Bool, extra: [AnyHashable : Any]) {
        
    }
    
    func rewardedVideoDidRewardSuccess(forPlacemenID placementID: String, extra: [AnyHashable : Any]) {
        print("视频激励已获取")
        finishVideoCallBack?()
    }
    
}

extension NewADTools: ATInterstitialDelegate {
    func interstitialDidShow(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
        isShowFullScreen = true
    }
    
    func interstitialDidClick(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
    
    }
    
    func interstitialDidClose(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
        isShowFullScreen = false
        didCloseFullScreenCallBack?()
    }
    
    
}

